import WXRealLogUtil from "./WXRealLogUtil";

export enum RewardADReturn {
    PlayRewarded,
    NoAd,
    PlayNotEnd
}

export default class WXAD {

    static instance: WXAD = new WXAD();

    wx: any = window['wx']

    _bannerID = "adunit-29632c179961d330"
    _bannerCellID = "adunit-1ee58f0511fc7c0d"
    _rewardID = "adunit-f57fc5e786cf81b5"
    _interstitialID = "adunit-b85f884d760cfbf9"

    _bannerInstance = null
    _bannerCellInstance = null;
    _rewardInstance = null
    _interstitialInstance = null;

    _bannerNeedShow = false;
    _bannerCellNeedShow = false;

    _bannerShowing = false
    _bannerCellShowing = false

    _rewardCallBack: (code: number) => void = null;

    public load() {
        console.log("[WX广告]开始加载")
        this._loadBanner();
        this._loadReward();
        this._loadBannerCell();
        this._loadInterstitial();
    }

    public showBanner() {
        if (this._bannerShowing)
            return
        if (this.wx == undefined)
            return
        if (this._bannerInstance) {
            console.log("[WX广告]横幅加载成功，展示")
            this._bannerShowing = true
            this._bannerInstance.show().catch(
                (err) => {
                    if (err)
                        console.log("[WX广告]横幅展示出错:", err)
                    else
                        console.log("[WX广告]横幅展示成功")
                }
            );
        } else {
            this._bannerNeedShow = true;
            console.log("[WX广告]横幅加载没成功，待展示")
        }
    }

    public showBannerCell() {
        if (this._bannerCellShowing)
            return
        if (this.wx == undefined)
            return
        if (this._bannerCellInstance) {
            // console.log("[WX广告]横幅格子加载成功，展示")
            this._bannerCellShowing = true
            this._bannerCellInstance.show().catch(
                (err) => {
                    if (err)
                        console.log("[WX广告]横幅格子展示出错:", err)
                    else
                        console.log("[WX广告]横幅格子展示成功")
                }
            );
        } else {
            // console.log("[WX广告]横幅格子加载没成功，待展示")
            this._bannerCellNeedShow = true;
        }
    }

    public showReward(callback: (code: number) => void) {
        if (this.wx == undefined) {
            callback(RewardADReturn.PlayRewarded);
            return console.warn("不是微信环境")
        }
        if (this._rewardInstance) {
            this._rewardCallBack = callback
            //如果组件的某次自动拉取失败，那么之后调用的 show() 将会被 reject。
            //此时可以调用 RewardedVideoAd.load() 手动重新拉取广告
            this._rewardInstance.show()
                .catch(err => {
                    if (err) {
                        this._rewardInstance.load()
                        console.error('[WX广告]激励视频 广告显示错误:', err)
                        callback(RewardADReturn.NoAd)
                        this._rewardCallBack = null;
                    } else {
                        console.log('[WX广告]激励视频 广告显示成功')
                    }
                })
        }
    }

    public hideBanner() {
        if (this._bannerShowing == false)
            return
        if (this.wx == undefined)
            return
        this._bannerShowing = false
        if (this._bannerInstance)
            this._bannerInstance.hide();
        this._bannerNeedShow = false;
    }

    public hideBannerCell() {
        if (this._bannerCellShowing == false)
            return
        if (this.wx == undefined)
            return
        this._bannerCellShowing = false
        if (this._bannerCellInstance)
            this._bannerCellInstance.hide();
        this._bannerCellNeedShow = false;
    }

    public showInterstitial() {
        if (this.wx == undefined)
            return console.warn("不是微信环境")
        if (this._interstitialInstance) {
            this._interstitialInstance.show().catch((err) => {
                if (err) {
                    console.error('[WX广告]插屏 广告显示失败,', err)
                    WXRealLogUtil.info(`插屏广告显示失败: ${JSON.stringify(err)}`)
                } else {
                    console.log('[WX广告]插屏 广告显示成功')
                    WXRealLogUtil.info(`插屏广告显示成功`)
                }
            })
        }
    }

    private _loadBanner() {
        if (this.wx == undefined)
            return console.warn("不是微信环境")
        let adWidth = 320;
        let adHeight = adWidth * 9 / 16;
        const windowWidth = this.wx.getSystemInfoSync().windowWidth;
        const windowHeight = this.wx.getSystemInfoSync().windowHeight;
        let banner = this.wx.createCustomAd({
            adUnitId: this._bannerID,
            style: {
                left: (windowWidth - adWidth) / 2,
                top: windowHeight - adHeight,
                width: adWidth
            }
        })
        banner.onError(err => {
            // console.log("[WX广告]横幅出错:", err)
            // WXRealLogUtil.info(`[WX广告]横幅加载出错: ${JSON.stringify(err)}`)
            setTimeout(() => {
                this._loadBanner();
            }, 5000)
        })
        banner.onLoad(() => {
            // console.log('[WX广告]横幅加载成功')
            // WXRealLogUtil.info(`[WX广告]横幅加载成功`)
            this._bannerNeedShow && this.showBanner();
            console.log("[WX广告]banner:", banner)
        })
        banner.onResize?.((res) => {
            console.log('[WX广告]横幅onResize:', res)
            // WXRealLogUtil.info(`[WX广告]横幅onResize: ${JSON.stringify(res)}`)
            if (res) {
                banner.style.top = windowHeight - res.height
                banner.style.left = (windowWidth - res.width) / 2
            }
        })
        this._bannerInstance = banner
        console.log(`[WX广告]横幅请求加载`)
    }

    private _loadBannerCell() {
        if (this.wx == undefined)
            return console.warn("不是微信环境")
        let adWidth = 90;
        const windowWidth = this.wx.getSystemInfoSync().windowWidth;
        const windowHeight = this.wx.getSystemInfoSync().windowHeight;
        console.log(`[WX广告] windowWidth:${windowWidth}, windowHeight:${windowHeight}`)
        let banner = this.wx.createCustomAd({
            adUnitId: this._bannerCellID,
            style: {
                left: (windowWidth - adWidth * 0.7),
                top: windowHeight * 0.5 - 100,
                width: adWidth
            }
        })
        banner.onError(err => {
            // console.log("[WX广告]横幅格子出错:", err)
            // WXRealLogUtil.info(`[WX广告]格子加载出错: ${JSON.stringify(err)}`)
            setTimeout(() => {
                this._loadBannerCell();
            }, 5000)
        })
        banner.onLoad(() => {
            // console.log('[WX广告]横幅格子加载成功2:', banner)
            WXRealLogUtil.info(`[WX广告]格子加载成功`)
            this._bannerCellNeedShow && this.showBannerCell();
            if (banner.style)
                banner.style.left = (windowWidth - banner.style.width * 0.7)
        })
        this._bannerCellInstance = banner
        console.log(`[WX广告]横幅格子请求加载}`)
    }

    private _loadReward() {
        if (this.wx == undefined)
            return console.warn("不是微信环境")
        if (this._rewardID.length == 0)
            return console.error("未设置视频广告ID");
        console.log("[WX广告]激励视频请求加载")
        let rewardedVideoAd = this.wx.createRewardedVideoAd({ adUnitId: this._rewardID })
        rewardedVideoAd.onLoad(() => {
            console.log('[WX广告]激励视频 广告加载成功')
        })
        rewardedVideoAd.onError(err => {
            console.log('[WX广告]激励视频 广告加载失败:', err)
        })
        this._rewardInstance = rewardedVideoAd
        this._rewardInstance.onClose(res => {
            // 用户点击了【关闭广告】按钮
            // 小于 2.1.0 的基础库版本，res 是一个 undefined
            if (res && res.isEnded || res === undefined) {
                // 正常播放结束，可以下发游戏奖励
                this._rewardCallBack && this._rewardCallBack(RewardADReturn.PlayRewarded)
            }
            else {
                // 播放中途退出，不下发游戏奖励
                this._rewardCallBack && this._rewardCallBack(RewardADReturn.PlayNotEnd)
            }
            this._rewardCallBack = null
            console.log("调用wx视频收到onclose")
        })
    }

    private _loadInterstitial() {
        if (this.wx == undefined)
            return console.warn("不是微信环境")
        let interstitialAd = this.wx.createInterstitialAd({ adUnitId: this._interstitialID })
        interstitialAd.onLoad(() => {
            console.log('[WX广告]插屏广告加载成功')
            // this.showInterstitial();
        })
        interstitialAd.onClose(res => {
            console.log('[WX广告]插屏广告关闭')
        })
        interstitialAd.onError(err => {
            console.log('[WX广告]', err)
        })
        this._interstitialInstance = interstitialAd;
    }
}
